package com.schoolMall.controller.shopAdmin;

import com.schoolMall.domain.Area;
import com.schoolMall.domain.Shop;
import com.schoolMall.domain.ShopCategory;
import com.schoolMall.domain.User;
import com.schoolMall.dto.ImageHolder;
import com.schoolMall.dto.ShopDto;
import com.schoolMall.enums.ShopStateEnum;
import com.schoolMall.exception.ShopOperationException;
import com.schoolMall.service.AreaService;
import com.schoolMall.service.ShopCategoryService;
import com.schoolMall.service.ShopService;
import com.schoolMall.utils.CodeUtil;
import com.schoolMall.utils.HttpServletRequestUtil;
import com.schoolMall.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @author:zyh
 * @Time:2021-08-29-16:27
 * @email:1269231889@qq.com
 */
@Controller
@RequestMapping("/schoolMall/shopManagement")
public class ShopManagementController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;

    private Logger logger = LoggerFactory.getLogger(ShopManagementController.class);

    @ResponseBody
    @GetMapping("/getShopCategory")
    public Map<String, Object> getShopCategory() {
        HashMap<String, Object> model = new HashMap<>();
        try {
            List<ShopCategory> shopCategoryList = shopCategoryService.queryShopCategoryList(new ShopCategory());
            List<Area> areaList = areaService.getAreaList();
            model.put("shopCategoryList", shopCategoryList);
            model.put("areaList", areaList);
            model.put("success", true);
            logger.info("model:{}", model);
        } catch (Exception e) {
            model.put("success", false);
            model.put("msg", e.toString());
        }
        return model;
    }


    @ResponseBody
    @PostMapping("/registerShop")
    public Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>(4);

        if (CollectionUtils.isEmpty(model = verifyCode(request))) {
            return model;
        }

        //接收参数并转化参数
        String shopMsg = HttpServletRequestUtil.getString(request, "shopMsg");
        Shop shop = null;
        try {
            shop = JsonUtil.json2Object(shopMsg, Shop.class);
        } catch (IOException e) {
            model.put("success", false);
            model.put("msg", e.toString());
            return model;
        }

        //从前端获取图片信息
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }

        try {
            if (Objects.nonNull(shop) && Objects.nonNull(shopImg)) {
                User owner = (User) request.getSession().getAttribute("user");
                shop.setOwner(owner);
                ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream());
                ShopDto shopExecution = shopService.addShop(shop, imageHolder);
                List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
                if (CollectionUtils.isEmpty(shopList)) {
                    shopList = new ArrayList<>();
                }
                shopList.add(shop);
                request.setAttribute("shopList", shopList);
                model.put("success", true);
                model.put("msg", shopExecution);
            } else {
                model.put("success", false);
                model.put("msg", "输入店铺信息");
                return model;
            }
        } catch (IOException | ShopOperationException e) {
            model.put("success", false);
            model.put("msg", e.toString());
        }
        return model;
    }

    @ResponseBody
    @GetMapping("/getShopById")
    public Map<String, Object> getShopById(HttpServletRequest request) {
        HashMap<String, Object> model = new HashMap<>();
        long shopId = HttpServletRequestUtil.getLong(request, "shopId");
        if (shopId < -1) {
            model.put("success", false);
            model.put("msg", "店铺不存在");
            return model;
        }
        Shop shop = shopService.queryShopById(shopId);
        List<Area> areaList = areaService.getAreaList();
        model.put("shop", shop);
        model.put("areaList", areaList);
        return model;
    }


    @ResponseBody
    @PostMapping("/modifyShop")
    public Map<String, Object> modifyShop(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        if (!CollectionUtils.isEmpty(model = verifyCode(request))) {
            return model;
        }
        //接收参数并转化参数
        String shopMsg = HttpServletRequestUtil.getString(request, "shopMsg");
        logger.info("shopMsg:{}", shopMsg);
        Shop shop = null;
        try {
            shop = JsonUtil.json2Object(shopMsg, Shop.class);
        } catch (IOException e) {
            model.put("success", false);
            model.put("msg", e.toString());
            return model;
        }

        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }


        try {
            if (Objects.nonNull(shop) && Objects.nonNull(shop.getShopId())) {
                User owner = (User) request.getSession().getAttribute("user");
                shop.setOwner(owner);
                ShopDto shopDto = null;
                if (Objects.isNull(shopImg)) {
                    shopDto = shopService.modifyShop(shop, null);
                } else {
                    ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream());
                    shopDto = shopService.modifyShop(shop, imageHolder);
                }
                if (shopDto.getCode() == ShopStateEnum.SUCCESS.getState()) {
                    model.put("success", true);
                    model.put("msg", shopDto.getMsg());
                } else {
                    model.put("success", false);
                    model.put("msg", shopDto.getMsg());
                }
            } else {
                model.put("success", false);
                model.put("msg", "输入店铺信息");
                return model;
            }
        } catch (IOException | ShopOperationException e) {
            model.put("success", false);
            model.put("msg", e.toString());
        }
        return model;
    }


    private Map<String, Object> verifyCode(HttpServletRequest request) {
        HashMap<String, Object> model = new HashMap<>();
        if (!CodeUtil.checkVerifyCode(request)) {
            logger.info("code error");
            model.put("success", false);
            model.put("msg", "验证码错误");
            return model;
        }
        return model;
    }
}
